<template>
  <el-card v-loading="loading">
    <template #header>
      <div class="card-header">
        <span>访问来源</span>
      </div>
    </template>
    <div ref="chartRef" class="chart"></div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getVisitorSource } from '@/api/visitor'
import { ElMessage } from 'element-plus'

interface SourceData {
  source: string
  count: number
}

const loading = ref(false)
const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
}

const updateChart = (data: SourceData[]) => {
  if (!chartInstance) return

  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)',
      confine: true,
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#eee',
      borderWidth: 1,
      padding: [5, 10],
      textStyle: {
        color: '#333'
      },
      extraCssText: 'box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      padding: 5,
      itemGap: 10,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: '50%',
        center: ['60%', '50%'],
        data: data.map((item, index) => ({
          name: item.source,
          value: item.count,
          itemStyle: {
            color: colors[index % colors.length]
          }
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{d}%',
          fontSize: 12,
          alignTo: 'edge',
          edgeDistance: '10%'
        },
        labelLine: {
          length: 10,
          length2: 10,
          smooth: true
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

const fetchData = async () => {
  loading.value = true
  try {
    const res = await getVisitorSource()
    updateChart(res.data)
  } catch (error) {
    console.error('获取访问来源数据失败:', error)
    ElMessage.error('获取访问来源数据失败')
  } finally {
    loading.value = false
  }
}

const handleResize = () => {
  chartInstance?.resize()
}

onMounted(() => {
  initChart()
  fetchData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance?.dispose()
})

// 监听主题变化，重新渲染图表
watch(
  () => document.documentElement.className,
  () => {
    if (chartInstance) {
      chartInstance.dispose()
      initChart()
      fetchData()
    }
  }
)
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 300px;
  position: relative;
  overflow: hidden;
}
</style> 